<template>
  <el-form v-bind="$attrs" @validate="formValidate">
    <el-form-item label="名称" prop="name" :rules="[{ required: true, message: '名称不能为空' }]">
      <el-input
        v-model="formData.name"
        :maxlength="50"
        placeholder="请输入数据标题，不超过50个字符"
      />
    </el-form-item>
    <el-form-item label="资源描述" prop="desc">
      <el-input
        v-model="formData.desc"
        type="textarea"
        :rows="1"
        autosize
        :maxlength="200"
        @keyup.enter.native="specialFormValidate('desc')"
        placeholder="请输入数据的描述信息，不超过200个字符"
      />
    </el-form-item>
    <el-form-item label="样式">
      <div class="row-item">
        <div class="style-image flex-row">
          <div class="style-image-wrap">
            <el-image :src="formData.attr.imageUrl"></el-image>
          </div>
          <div class="style-image-btn" @click="picChange">替换样式</div>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="贴地">
      <el-switch
        v-model="formData.attr.heightReference"
        active-text="开"
        inline-prompt
        inactive-text="关"
        @change="specialFormValidate('heightReference')"
      >
      </el-switch>
    </el-form-item>
    <el-form-item label="闪烁">
      <el-switch
        v-model="formData.attr.isBlink"
        inline-prompt
        active-text="开"
        inactive-text="关"
        @change="specialFormValidate('isBlink')"
      >
      </el-switch>
    </el-form-item>
    <el-collapse v-model="activeNames">
      <el-collapse-item title="标签" name="1">
        <el-form-item label="标签内容">
          <el-input
            v-model="formData.attr.infoValue"
            placeholder=""
            :maxlength="50"
            @keyup.enter.native="specialFormValidate('infoValue')"
          />
        </el-form-item>
        <el-form-item label="">
          <div class="row-item">
            <div class="row-item-col column">
              <div class="title">标签颜色</div>
              <div class="content">
                <el-color-picker
                  v-model="formData.attr.infoFillColor"
                  @change="specialFormValidate('infoFillColor')"
                />
                <el-input
                  class="ml10"
                  v-model="formData.attr.infoFillColor"
                  placeholder=""
                  disabled
                />
              </div>
            </div>
            <div class="row-item-col column">
              <div class="title">字号</div>
              <div class="content">
                <el-input-number
                  v-model="formData.attr.infoFont"
                  controls-position="right"
                  placeholder=""
                  :step="1"
                  :min="1"
                  :max="100"
                  @keyup.enter.native="specialFormValidate('infoFont')"
                  @change="specialFormValidate('infoFont')"
                />
              </div>
            </div>
          </div>
          <div class="row-item">
            <div class="row-item-col column">
              <div class="title">标签偏移</div>
              <div class="content">
                <el-input-number
                  v-model="formData.attr.infoOffset[0]"
                  controls-position="right"
                  @keyup.enter.native="specialFormValidate('infoOffset')"
                  @change="specialFormValidate('infoOffset')"
                />
                <el-input-number
                  class="ml10"
                  v-model="formData.attr.infoOffset[1]"
                  controls-position="right"
                  @keyup.enter.native="specialFormValidate('infoOffset')"
                  @change="specialFormValidate('infoOffset')"
                />
                <el-input-number
                  class="ml10"
                  v-model="formData.attr.infoOffset[2]"
                  controls-position="right"
                  @keyup.enter.native="specialFormValidate('infoOffset')"
                  @change="specialFormValidate('infoOffset')"
                />
              </div>
            </div>
          </div>
          <div class="row-item">
            <div class="row-item-col column">
              <div class="title">排列方向</div>
              <div class="content">
                <el-radio-group
                  v-model="formData.attr.infoVertical"
                  @change="specialFormValidate('infoVertical')"
                >
                  <el-radio :label="false">横向</el-radio>
                  <el-radio :label="true">纵向</el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
          <!-- <div class="row-item">
            <div class="row-item-col column">
              <div class="title">跟踪镜头</div>
              <div class="content">
                <el-switch
                  v-model="formData.attr.heightReference"
                  @change="specialFormValidate('heightReference')"
                >
                </el-switch>
              </div>
            </div>
          </div> -->
        </el-form-item>
      </el-collapse-item>
      <el-collapse-item title="尺寸" name="2">
        <el-form-item label="">
          <div class="row-item">
            <div class="title">宽度</div>
            <el-input-number
              v-model="formData.attr.imageWidth"
              placeholder=""
              :controls="false"
              :min="0"
              @keyup.enter.native="specialFormValidate('imageWidth')"
            />
            <div class="unit">米</div>
          </div>
          <div class="row-item">
            <div class="title">高度</div>
            <el-input-number
              v-model="formData.attr.imageHeight"
              placeholder=""
              :controls="false"
              :min="0"
              @keyup.enter.native="specialFormValidate('imageHeight')"
            />
            <div class="unit">米</div>
          </div>
        </el-form-item>
      </el-collapse-item>
      <el-collapse-item title="位置" name="3">
        <el-form-item label="">
          <div class="row-item">
            <div class="title">经度</div>
            <el-input-number
              v-model="formData.attr.position[0]"
              placeholder=""
              :controls="false"
              :min="-180"
              :max="180"
              @keyup.enter.native="specialFormValidate('position')"
            />
            <div class="unit">°</div>
          </div>
          <div class="row-item">
            <div class="title">纬度</div>
            <el-input
              v-model="formData.attr.position[1]"
              placeholder=""
              :controls="false"
              :min="-90"
              :max="90"
              @keyup.enter.native="specialFormValidate('position')"
            />
            <div class="unit">°</div>
          </div>
          <div class="row-item">
            <div class="title">高度</div>
            <el-input-number
              v-model="formData.attr.position[2]"
              placeholder=""
              :controls="false"
              :precision="2"
              @keyup.enter.native="specialFormValidate('position')"
            />
            <div class="unit">米</div>
          </div>
        </el-form-item>
        <el-form-item label="跟踪镜头">
          <el-switch v-model="flagObj.track" inline-prompt active-text="开" inactive-text="关">
          </el-switch>
        </el-form-item>
      </el-collapse-item>
      <el-collapse-item title="跟随缩放" name="4">
        <el-form-item label="默认常显">
          <el-switch
            v-model="formData.attr.defaultShow"
            inline-prompt
            active-text="开"
            inactive-text="关"
            @change="specialFormValidate('defaultShow')"
          >
          </el-switch>
          <!-- <el-switch v-model="formData.attr.isBlink" @change="specialFormValidate('isBlink')">
          </el-switch> -->
        </el-form-item>
        <el-form-item>
          <template #label>
            <span>显示距离</span>&nbsp;&nbsp; <span>缩放范围（m）</span>&emsp;&emsp;
            <span>缩放比率</span>
          </template>
          <div class="row-item scale-wrap">
            <div class="title">最小距离</div>
            <el-input-number
              v-model="formData.attr.scaleByDistanceArray[0]"
              placeholder=""
              :controls="false"
              :precision="2"
              :min="0"
              @keyup.enter.native="specialFormValidate('scaleByDistanceArray')"
              :disabled="formData.attr.defaultShow"
            />
            <el-input-number
              v-model="formData.attr.scaleByDistanceArray[1]"
              placeholder=""
              :controls="false"
              :precision="2"
              :min="0"
              @keyup.enter.native="specialFormValidate('scaleByDistanceArray')"
              :disabled="formData.attr.defaultShow"
            />
          </div>
          <div class="row-item scale-wrap">
            <div class="title">最大距离</div>
            <el-input-number
              v-model="formData.attr.scaleByDistanceArray[2]"
              placeholder=""
              :controls="false"
              :precision="2"
              :min="0"
              @keyup.enter.native="specialFormValidate('scaleByDistanceArray')"
              :disabled="formData.attr.defaultShow"
            />
            <el-input-number
              v-model="formData.attr.scaleByDistanceArray[3]"
              placeholder=""
              :controls="false"
              :precision="2"
              :min="0"
              @keyup.enter.native="specialFormValidate('scaleByDistanceArray')"
              :disabled="formData.attr.defaultShow"
            />
          </div>
        </el-form-item>
      </el-collapse-item>
    </el-collapse>
  </el-form>
</template>

<script setup lang="ts">
import { messageUtil } from '@jl/element-plus/utils';
import { ValidateRule } from '@/views/enum/common';
import { notNumberInRange } from '@/utils';
import { useSceneStore } from '@/store/scene';

defineOptions({
  name: '',
});

interface IProps {
  form: any;
}

const props = withDefaults(defineProps<IProps>(), {
  form: {},
});

const sceneStore = useSceneStore();
const formData = ref<any>(null);
const emits = defineEmits(['picChange']);
const activeNames = ref<string[]>(['1', '2', '3', '4']);
const flagObj = ref({
  track: true,
  show: true,
});

function formValidate(fieldName: string, valid: boolean) {
  // emits('formValidate', fieldName, valid);
  updateAttr(fieldName, valid);
}

function specialFormValidate(fieldName: string) {
  let valid = true;
  if (['desc'].includes(fieldName)) {
    if (formData.value[fieldName].length > 200) {
      valid = false;
    }
  }
  if (['position'].includes(fieldName)) {
    formData.value.attr[fieldName].forEach((list: any, index: number) => {
      if (list === '' || isNaN(list)) {
        valid = false;
      }
      const min = ValidateRule[fieldName][index].min;
      const max = ValidateRule[fieldName][index].max;
      if (min && notNumberInRange(list, min, max)) {
        valid = false;
      }
    });
  }
  if (['scaleByDistanceArray', 'infoOffset'].includes(fieldName)) {
    for (const list of formData.value.attr[fieldName]) {
      if (list === '' || isNaN(list)) {
        valid = false;
      }
    }
  } else if (['imageWidth', 'imageHeight', 'infoFont'].includes(fieldName)) {
    if (formData.value.attr[fieldName] === '' || isNaN(formData.value.attr[fieldName])) {
      valid = false;
    }
  }
  if (!valid) {
    messageUtil.warning('校验错误');
  }
  updateAttr(fieldName, valid);
  // emits('formValidate', fieldName, valid);
}

function updateAttr(fieldName: string, valid: boolean) {
  const { cimInstance } = window;
  sceneStore.editError = !valid;
  if (sceneStore.editError || !sceneStore.selLayer) return;
  let imageParam: any = {
    imageUrl: sceneStore.selLayer.attr.imageUrl,
    imageWidth: Number(sceneStore.selLayer.attr.imageWidth),
    imageHeight: Number(sceneStore.selLayer.attr.imageHeight),
    imageScale: 1, // 标签闪烁
    imageIsBlink: sceneStore.selLayer.attr.isBlink, // 标签闪烁
    imageHeightReference: sceneStore.selLayer.attr.heightReference ? 'CLAMP_TO_GROUND' : 'NONE', // 标签贴地
    imageScaleByDistanceArray: sceneStore.selLayer.attr.scaleByDistanceArray.map((v: any) =>
      Number(v)
    ),
  };
  let infoParam: any = {
    infoValue: sceneStore.selLayer.attr.infoValue,
    infoFillColor: sceneStore.selLayer.attr.infoFillColor,
    infoFont: sceneStore.selLayer.attr.infoFont + 'px 微软雅黑',
    infoOffset: sceneStore.selLayer.attr.infoOffset.map((v: any) => Number(v)),
    infoVertical: sceneStore.selLayer.attr.infoVertical,
    infoHeightReference: sceneStore.selLayer.attr.heightReference ? 'CLAMP_TO_GROUND' : 'NONE', // 标签贴地
    infoScaleByDistanceArray: sceneStore.selLayer.attr.scaleByDistanceArray.map((v: any) =>
      Number(v)
    ),
  };
  if (sceneStore.selLayer.attr.defaultShow) {
    imageParam = {
      ...imageParam,
      imageMinDisplayDistance: 0,
      imageMaxDisplayDistance: 10000000000000000,
    };
    infoParam = {
      ...infoParam,
      infoMinDisplayDistance: 0,
      infoMaxDisplayDistance: 10000000000000000,
    };
  } else {
    imageParam = {
      ...imageParam,
      imageMinDisplayDistance: 0,
      imageMaxDisplayDistance: 10000,
    };
    infoParam = {
      ...infoParam,
      infoMinDisplayDistance: 0,
      infoMaxDisplayDistance: 10000,
    };
  }
  cimInstance.api.updateGraphicById(sceneStore.selLayer.layerName, '0_image', {
    image: imageParam,
    coordinates: sceneStore.selLayer.attr.position.map((v: any) => Number(v)),
  });
  cimInstance.api.updateGraphicById(sceneStore.selLayer.layerName, '0_info', {
    info: infoParam,
    coordinates: sceneStore.selLayer.attr.position.map((v: any) => Number(v)),
  });
  if (sceneStore.effectDotState) {
    sceneStore.effectTemporaryAttr = {
      ...imageParam,
      ...infoParam,
      infoFont: infoParam.infoFont.split('px')[0],
      defaultShow: sceneStore.selLayer.attr.defaultShow,
    };
    if (sceneStore.poiEffectTemporaryLayernames.length > 2) {
      const lastLayerName =
        sceneStore.poiEffectTemporaryLayernames[sceneStore.poiEffectTemporaryLayernames.length - 1];
      if (lastLayerName === 'test') return;
      sceneStore.poiEffectTemporaryLayernames = ['test', lastLayerName, 'test'];
    }
  }
}

function picChange() {
  emits('picChange');
}

watchEffect(() => {
  formData.value = props.form;
});

function picChangeCallBack(src: string) {
  if (!sceneStore.selLayer) return;
  sceneStore.selLayer.attr.imageUrl = src;
  specialFormValidate('imageUrl');
}

defineExpose({ picChangeCallBack });
</script>

<style lang="less" scoped>
.el-form {
  &-item {
    .row-item {
      width: 100%;
      display: flex;
      margin-bottom: 10px;
      .title {
        flex: 0 0 40px;
      }
      .el-input,
      .el-input-number {
        flex: 1;
      }
      .unit {
        flex: 0 0 24px;
        text-align: center;
      }

      &.scale-wrap {
        .title {
          flex: 0 0 68px;
        }
        .el-input-number {
          margin-right: 20px;
          &:last-child {
            margin-right: 0px;
          }
        }
      }
      &:last-child {
        margin-bottom: 0px;
      }
    }
  }
}
</style>
